﻿using UnityEngine;  
using System.Collections;  
  
public class Rotate : MonoBehaviour  
{
    public GameObject target;                //目标物体
    public float MouseScrollSensitivity = 1; //滑动滚轮灵敏度
    public float MaxDistance;                //摄像机离物体的最大距离
    public float MinDistacne = 3f;           //摄像机离物体的最小距离
    Vector3 StartPosition;  
    Vector3 previousPosition;  
    Vector3 offset;  
    Vector3 finalOffset;  
    Vector3 eulerAngle;
    Vector3 direc;
  
    bool isSlide;  
    float angle;
    void Start()
    {
        Vector3 Direction = this.transform.position - target.transform.position; //摄像机和目标物体的偏移向量
        direc = Direction.normalized;                                            //把该偏移向量单位化
        MaxDistance = Direction.magnitude;                                       //计算摄像机和目标物体之间最大距离（也就是运行时两者距离）
    }
 
    void Update()
    {  
        if (Input.GetMouseButtonDown(0))  
       {  
            StartPosition = Input.mousePosition;  
            previousPosition = Input.mousePosition;  
        }  
        else if (Input.GetMouseButton(0))  
        {  
            offset = Input.mousePosition - previousPosition;  
            previousPosition = Input.mousePosition;  
            target.transform.Rotate(Vector3.Cross(offset, Vector3.forward).normalized * 0.5f, offset.magnitude, Space.World);  
        }  
       else if (Input.GetMouseButtonUp(0))  
        {  
            finalOffset = Input.mousePosition - StartPosition;  
            isSlide = true;  
           angle = finalOffset.magnitude;  
        }  
       if (isSlide)  
       {
            target.transform.Rotate(Vector3.Cross(finalOffset, Vector3.forward).normalized * 0.5f, angle* 2 * Time.deltaTime, Space.World);  
           if (angle > 0)  
            {  
                angle -= 8;  
           }  
            else  
           {  
                angle = 0;  
            }  
        }  

       if(Input.GetAxis("Mouse ScrollWheel") != 0)   //如果监测到滚轮滑动
        {
            float Offset = Input.GetAxis("Mouse ScrollWheel") * MouseScrollSensitivity; //获取滚动的长度
            Vector3 tmp = this.transform.position - Offset * direc;                     //根据滚动长度暂时确定摄像机坐标
            float tmpDistance = (tmp-target.transform.position).magnitude;              //计算暂时摄像机坐标和目标之间的距离
            if(tmpDistance <= MaxDistance && tmpDistance >= MinDistacne)                //如果距离在要求范围之内，就改变摄像机位置
            {
                this.transform.position = tmp;
            }
        }
    }  
}  
